// api/routes/ai_routes.go
package routes

import (
	"mygin/api/handlers"
	"mygin/api/middleware"
	"mygin/internal/repositories"
	"mygin/internal/services"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// CORS中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

func RegisterAiRoutes(r *gin.RouterGroup, db *gorm.DB) {
	// 直接创建handler，不需要db或service
	// 创建 AliyService 实例
	userRepo := repositories.NewUserRepository(db)
	testRepo := repositories.NewTestRepository(db)
	aliyService := services.NewAliyService(testRepo, userRepo) // 假设有这样一个构造函数
	aliyHandler := handlers.NewAiHandler(aliyService)

	aiRoutes := r.Group("/ai", middleware.DecryptMiddleware(), CORSMiddleware())
	{
		//aiRoutes.GET("/ai", middleware.DecryptMiddleware(), aliyHandler.Ai)
		aiRoutes.GET("/ai", aliyHandler.Ai)
		aiRoutes.POST("/ai_chat", aliyHandler.AiChat)
		aiRoutes.GET("/gummy", aliyHandler.Gummy) //WebSocket连接要get方法

		aiRoutes.GET("/ws/:userID", aliyHandler.ConnectWebSocket) // WebSocket连接路由
		aiRoutes.POST("/ws/send", aliyHandler.SendMessage)        //发送消息API
		aiRoutes.OPTIONS("/ws/send", aliyHandler.SendMessage)

		// 其他简单路由...
	}
}
